#include <avr/io.h>
#include "../usbtiny/def.h"
#include "spi.h"
#include "i2c.h"

//I2C pin
#define SPI_SCK			7
#define SPI_MISO		6
#define SPI_MOSI		5

#define PIN_LOW(pin)		PORT_CLR(B, pin)
#define PIN_HIGH(pin)		PORT_SET(B, pin)

#define PIN_INPUT(pin)		DDR_CLR(B, pin)
#define PIN_OUTPUT(pin)		DDR_SET(B, pin)

#define spi_nop() 

#define SET_SCK()		do{ PIN_HIGH(SPI_SCK); spi_nop(); }while(0)
#define CLR_SCK()		do{ PIN_LOW(SPI_SCK);  spi_nop(); }while(0)

#define TOGGLE_SCK()	do{ (PINB = (1<<SPI_SCK));  spi_nop(); }while(0)

#define SET_MOSI()		do{ PIN_HIGH(SPI_MOSI); spi_nop(); }while(0)
#define CLR_MOSI()		do{ PIN_LOW(SPI_MOSI);  spi_nop(); }while(0)

#define GET_MISO()		(PINB & (1<<SPI_MISO))

void spi_init(unsigned char mode)
{
	if(mode) {
		SET_SCK();//mode 1
	} else {
		CLR_SCK();//mode 0
	}
	PIN_OUTPUT(SPI_SCK);
	PIN_OUTPUT(SPI_MOSI);
	PIN_HIGH(SPI_MISO);
	PIN_INPUT(SPI_MISO);
}

unsigned char spi_play_one_byte(unsigned char data)
{
	unsigned char ret_val = 0, mask = 0x80;

	do {
		if(mask & data) {
			SET_MOSI();
		} else {
			CLR_MOSI();
		}
		delay();
		TOGGLE_SCK();
		delay();
		if(GET_MISO()) {
			ret_val |= mask;
		}
		mask = mask >> 1;
		TOGGLE_SCK();
		delay();
	} while(mask);

	return ret_val;
}
